package com.fuhao.api.service.impl;

import java.util.Date;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;

import org.apache.activemq.command.ActiveMQQueue;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.fuhao.api.dao.MemberDao;
import com.fuhao.api.entity.UserEntity;
import com.fuhao.api.service.MemberService;
import com.fuhao.base.BaseApiService;
import com.fuhao.base.BaseRedisService;
import com.fuhao.base.ResponseBase;
import com.fuhao.constants.Constants;
import com.fuhao.mq.RegisterMailboxProducer;
import com.fuhao.utils.MD5Util;
import com.fuhao.utils.TokenUtils;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy;
import lombok.extern.slf4j.Slf4j;

@RestController
@Slf4j
public class MemberServiceImpl implements MemberService{
	@Autowired
	RegisterMailboxProducer registerMailboxProducer;
	@Autowired
	private MemberDao memberDao;
	@Value("${MESSAGEQUEUE}")
	private String MESSAGEQUEUE;
	@Autowired
	private BaseRedisService redisService; 
	//根据用户id获取用户信息
	@Override
	public ResponseBase findUserById(Long userId) {
		UserEntity userEntity = memberDao.findById(userId);
		if (userEntity==null) {
			return BaseApiService.setResultError("未查询到该用户");
		}
		return BaseApiService.setResultSuccess(userEntity);
	}
	//用户注册
	@Override
	public ResponseBase regUser(@RequestBody UserEntity userEntity) {
		String password = userEntity.getPassword();
		if(StringUtils.isEmpty(password)) {
			return BaseApiService.setResultError("密码不能未空");
		}
		String nPassword = MD5Util.MD5(password);
		userEntity.setPassword(nPassword);
		userEntity.setCreated(new Date());
		userEntity.setUpdated(new Date());
		Integer result = memberDao.insertUser(userEntity);
		if(result<= 0) {
			BaseApiService.setResultError("注册失败，请重试！");
		}
		log.info("==========发送邮件============");
		String email = userEntity.getEmail();
		//发送邮件信息
		String json = emailJson(email);
		log.info("邮箱为："+json);
		sendMsg(json);
		return BaseApiService.setResultSuccess("注册成功！");
	}
	
	/**
	 * 组装消息json
	 * @param email
	 * @return
	 */
	private String emailJson(String email) {
		JSONObject rootJSON = new JSONObject();
		JSONObject headJson = new JSONObject();
		JSONObject content = new JSONObject();
		headJson.put("interfaceType", Constants.MSG_EMAIL);
		content.put("email", email);
		rootJSON.put("content", content);
		rootJSON.put("header", headJson);
		return rootJSON.toJSONString();
	}
	/**
	 * 发送消息
	 * @param json
	 */
	private void sendMsg(String json) {
		log.info("创建的队列名字："+MESSAGEQUEUE);
		//创建队列
		ActiveMQQueue activeMQQueue = new ActiveMQQueue(MESSAGEQUEUE);
		registerMailboxProducer.sendMsg(activeMQQueue, json);
	}
	//账号密码登陆
	@Override
	public ResponseBase login(@RequestBody UserEntity userEntity) {
		//1.验证参数
		String username = userEntity.getUsername();
		if(StringUtils.isEmpty(username)) {
			return BaseApiService.setResultError("用户名不能为空");
		}
		String password = userEntity.getPassword();
		if(StringUtils.isEmpty(password)) {
			return BaseApiService.setResultError("密码不能为空");
		}
		//2.数据库查找验证账号密码
		String npassword = MD5Util.MD5(password);
		UserEntity user = memberDao.login(username, npassword);
		if(user == null) {
			return BaseApiService.setResultError("账号或密码不正确");
		}
		//判断用户之前是否登陆过
		return setLogin(user);
	}
	//抽取redis保存token代码
	private ResponseBase setLogin(UserEntity user) {
		//判断用户之前是否登陆过
				String string = (String) redisService.getString("loginSys"+user.getId());
				if(!StringUtils.isEmpty(string)) {
					redisService.delKey(string);
				}
				//3.若正确，生成token令牌
				String token = TokenUtils.getMemberToken();
				//4.token存到redis，key为token，value为userId
				redisService.setString(token, user.getId()+"", Constants.TOKEN_MEMBER_TIME);
				redisService.setString("loginSys"+user.getId(), token, Constants.TOKEN_MEMBER_TIME);
				//5.返回token
				JSONObject object = new JSONObject();
				object.put("token", token);
				return BaseApiService.setResultSuccess(object);
	}
	
	//当登陆了后，根据token返回用户信息
	@Override
	public ResponseBase findByTokenUser(@RequestParam("token") String token) {
		if(StringUtils.isEmpty(token)) {
			BaseApiService.setResultError("请重新登陆！");
		}
		String stringUserId = (String) redisService.getString(token);
		if(StringUtils.isEmpty(stringUserId)) {
			return BaseApiService.setResultError("请重新登陆！");
		}
		Long userId = Long.parseLong(stringUserId);
		UserEntity userEntity = memberDao.findById(userId);
		if(userEntity == null) {
			return BaseApiService.setResultError("未找到用户信息");
		}
		userEntity.setPassword(null);
		return BaseApiService.setResultSuccess(userEntity);
	}
	//根据openid获取用户信息
	@Override
	public ResponseBase findByOpenIdUser(@RequestParam("openid")String openid) {
		//1.验证参数
		if(StringUtils.isEmpty(openid)) {
			return BaseApiService.setResultError("openid不能为空");
		}
		//2.使用openid查询数据库获取对应的数据信息
		UserEntity user = memberDao.findByOpenIdUser(openid);
		if (user==null) {
			return BaseApiService.setResultError(Constants.HTTP_RES_CODE_201, "未关联qq账号");
		}
		//3.自动登陆
		return setLogin(user);
	}
	//qq绑定关联账号
	@Override
	public ResponseBase qqLogin(@RequestBody UserEntity userEntity) {
		//验证参数
		//获取openid
		String openid = userEntity.getOpenid();
		if(StringUtils.isEmpty(openid)) {
			return BaseApiService.setResultError("openId不能为空");
		}
		//进行账号登陆，
		ResponseBase base = login(userEntity);
		if(!base.getCode().equals(Constants.HTTP_RES_CODE_200)) {
			//失败
			return BaseApiService.setResultError("账号或密码错误");
		}
		//获取token,并且根据token获取到userid
		JSONObject jsonObject =  (JSONObject) base.getData();
		String token = jsonObject.getString("token");
		ResponseBase userToken = findByTokenUser(token);
		UserEntity user = (UserEntity) userToken.getData();
		//成功，修改数据库openid
		Integer updateByOpenIdUser = memberDao.updateByOpenIdUser(openid, user.getId());
		if(updateByOpenIdUser<=0) {
			return BaseApiService.setResultError("关联账号失败");
		}
		//返回token
		return base;
	}

}
